﻿using System.IO;
using ServerFramework.Tools;

namespace ServerFramework.Net.Msg
{
    /// <summary>
    /// 通用流接口
    /// </summary>
    public interface ISn
    {
        void Sn(MsgSn sn);

        void Usn(MsgUsn usn);

    }
    /// <summary>
    /// 
    /// </summary>
    public  class StreamMsg : MsgBase, ISn
    {
        protected override void WriteMsgId()
        {
            base.WriteMsgId();
        }
        public override byte[] Pack()
        {
            using (MsgSn sn = new MsgSn())
            {
                Sn(sn);
                byte[] DBuffer = sn.GetMsg();
                if (_compress)
                {
                    DBuffer = Zip.zip(DBuffer);
                }
                int totalLength = DBuffer.Length + MSG_HEAD_LENTH;
                byte[] msgBuffer = new byte[totalLength];
                using (MemoryStream stream = new MemoryStream(msgBuffer))
                {
                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write(totalLength);
                    writer.Write(_msgId);
                    writer.Write(_userId);
                    writer.Write(_status);
                    writer.Write(DBuffer);
                }
                _lenth = totalLength;
                return msgBuffer;
            }
        }

        public override void Unpack(MsgPacket packet)
        {
            base.Unpack(packet);
            if (_compress)
            {
                packet.data = Zip.unzip(packet.data);
            }
            using (MsgUsn usn = new MsgUsn(packet.data))
            {
                Usn(usn);
            }
        }

        public virtual  void Sn(MsgSn sn)
        {
        }
        public virtual  void Usn(MsgUsn usn)
        {

        }
    }
}
